package org.example.maven.controller;

import jakarta.transaction.Transactional;
import org.example.maven.annotation.ReadOnlyMode;
import org.example.maven.annotation.logAnnotation;
import org.example.maven.pojo.Result;
import org.example.maven.pojo.Review.ReviewCollectionIds;
import org.example.maven.pojo.Review.ReviewCollectionSpecie;
import org.example.maven.pojo.Review.ReviewStats;
import org.example.maven.pojo.list.ListTableCollection;
import org.example.maven.pojo.utils.CollectionJpa;
import org.example.maven.pojo.utils.SearchCollection;
import org.example.maven.pojo.utils.AddTemp;
import org.example.maven.service.ProvenanceSourceService;
import org.example.maven.service.CollectionService;
import org.example.maven.utils.JwtUtils;
import org.example.maven.utils.ThreadlocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/collection")
public class CollectionController {
    @Autowired
    private CollectionService collectionServiceImpl;
    @Autowired
    private ProvenanceSourceService provenanceSourceServiceImpl;
    @GetMapping
    //获取所有藏品listTable信息
    @PreAuthorize("permitAll()")
    public Result getList(@RequestParam("pageNum") int pageNum,@RequestParam("pageSize") int pageSize){
        Result res=Result.success();
        res.put("data",collectionServiceImpl.getList(pageNum,pageSize));
        res.put("total",collectionServiceImpl.getCollectionNumber(new SearchCollection()));
        return res;
    }

    @GetMapping("/getListNumber")
    //获取藏品的总数
    @PreAuthorize("permitAll()")
    public Result getListNumber(){
        return Result.success("操作成功",collectionServiceImpl.getCollectionNumber(new SearchCollection()));
    }

    @GetMapping("/getSpecificCollection")
    //获取特定的藏品
    @PreAuthorize("permitAll()")
    public Result getSpecificCollection(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize, @ModelAttribute SearchCollection searchCollection){
        Result res=Result.success();
        res.put("data",collectionServiceImpl.getSpecificCollection(pageNum,pageSize,searchCollection));
        res.put("total",collectionServiceImpl.getCollectionNumber(searchCollection));
        System.out.println(collectionServiceImpl.getCollectionNumber(searchCollection));
        return res;
    }

    @GetMapping("/getOneCollection")
    //获取藏品的详细信息
    @PreAuthorize("permitAll()")
    public Result getCollectionDetail(@RequestParam("id") Integer id){
        return Result.success(collectionServiceImpl.getCollectionDetail(id));
    }

    @GetMapping("/getEditCollection")
    @ReadOnlyMode
    //获取编辑藏品的详细信息
    @PreAuthorize("hasAnyAuthority('collection:all')")
    public Result getEditCollection(@RequestParam("id") Integer id){
        return Result.success(collectionServiceImpl.getCollectionEditDetailById(id));
    }

    @PatchMapping()
    @ReadOnlyMode
    @logAnnotation(
            type = "更新",
            detail = "审核藏品"
    )
    //进行藏品审核的通过
    @PreAuthorize("hasAnyAuthority('collection:review')")
    public Result updateCollectionReview(@RequestBody ReviewCollectionIds id){
        if(id!=null&&id.getId().length!=0){
            collectionServiceImpl.updateCollectionReview(id.getId());
        }
        return Result.success();
    }

    @PutMapping()
    @ReadOnlyMode
    @logAnnotation(
            type = "更新",
            detail = "修改藏品{#collectionJpa.name}"
    )
    //进行藏品的信息更新
    @PreAuthorize("hasAnyAuthority('collection:all')")
    public Result updateCollection(@RequestBody CollectionJpa collectionJpa){
        collectionServiceImpl.updateCollection(collectionJpa);
        return Result.success();
    }
    @PostMapping
    @Transactional
    @ReadOnlyMode
    @logAnnotation(
            type = "新增",
            detail = "新增藏品{#addTemp.listTableCollectionAddDetail.name}"
    )
    //添加藏品
    @PreAuthorize("hasAnyAuthority('collection:add')")
    public Result addCollection(@RequestBody AddTemp addTemp){
        collectionServiceImpl.addCollection(addTemp.getListTableCollectionAddDetail());
        addTemp.getProvenanceSource().setCollectionId(addTemp.getListTableCollectionAddDetail().getId());
        provenanceSourceServiceImpl.addProvenanceSource(addTemp.getProvenanceSource());
        // 从 ThreadLocal 获取 claims 对象
        Map<String, Object> claims = JwtUtils.Parse(ThreadlocalUtils.get());

        if (claims != null) { // 确保类型安全
            Object idValue = ((Map<?, ?>) claims).get("id");
            if (idValue != null) {
                // 转换为具体类型（假设 id 是 Long 或 Integer）
                Integer id = Integer.parseInt(idValue.toString());
                // 使用 id
                collectionServiceImpl.addReviewCollection(addTemp.getProvenanceSource().getCollectionId(), id);
            } else {
                throw new RuntimeException("JWT 中缺少 id 字段");
            }
        } else {
            throw new RuntimeException("JWT claims 格式不符合预期");
        }
        return Result.success();
    }

    @GetMapping("/getReviewCollection")

    //获取需要审核的藏品总数，以及今日新增的待审核藏品总数
    @PreAuthorize("permitAll()")
    public Result getReviewCollection(){
        //获取审核藏品数
        Integer CollectionReviewCount= collectionServiceImpl.getCollectionReview(new ReviewCollectionSpecie());
        //获取今日新增藏品数
        Integer CollectionReviewDayCount=collectionServiceImpl.getCollectionReviewDay();
        return Result.success(new ReviewStats(CollectionReviewCount,CollectionReviewDayCount));
    }

    @GetMapping("/getReviewCollectionDetail")
    //获取待审核藏品信息
    @PreAuthorize("permitAll()")
    public Result getReviewCollectionDetail(@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize){
        return Result.success(collectionServiceImpl.getCollectionReviewListTable(pageNum,pageSize));
    }

    @GetMapping("/getSpecieReviewCollection")
    //获取特定的待审核藏品
    @PreAuthorize("permitAll()")
    public Result getSpecieReviewCollection(@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize,@ModelAttribute ReviewCollectionSpecie reviewCollectionSpecie){
        Result res=Result.success("查询成功");
        //System.out.println(reviewCollectionSpecie);
        res.put("data",collectionServiceImpl.getSpecieReviewCollection(pageNum,pageSize,reviewCollectionSpecie));
        res.put("total",collectionServiceImpl.getCollectionReview(reviewCollectionSpecie));
        return res;
    }

}
